package com.zd.wechatPlatform.service.impl.msgHandler;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zd.wechatPlatform.bean.model.WxAccount;
import com.zd.wechatPlatform.bean.model.WxFeebackMsg;
import com.zd.wechatPlatform.bean.vo.WxFeebackMsgVo;
import com.zd.wechatPlatform.cache.map.WxAccountCache;
import com.zd.wechatPlatform.common.enums.FeebackMsgTypeEnum;
import com.zd.wechatPlatform.common.utils.LogUtils;
import com.zd.wechatPlatform.common.utils.WeixinInterfaceUtil;
import com.zd.wechatPlatform.service.IWxClickMsgService;

/**
 * 微信点击事件处理器
 * 
 * @author lishi
 * @date 2018年11月1日 上午10:06:53
 */
@Service("clickEventMsgHandler")
public class WeixinClickEventMsgHandler extends WeixinEventMsgHandler {
	@Autowired
	private IWxClickMsgService wxClickMsgService;

	@Autowired
	private WxAccountCache wxAccountCache;

	@Override
	public void handlerMsg(Map<String, String> msgMap) throws Exception {
		String accountId = msgMap.get("ToUserName");
		String openId = msgMap.get("FromUserName");
		String eventKey = msgMap.get("EventKey");

		WxAccount wxAccount = wxAccountCache.get(accountId);
		if (wxAccount != null) {
			List<WxFeebackMsg> feebackMsgList = wxClickMsgService.getClickMsg(wxAccount.getId(), eventKey);

			String accessToken = wxAccount.getAccessToken();

			if (feebackMsgList != null && feebackMsgList.size() > 0) {
				for (WxFeebackMsg feebackMsg : feebackMsgList) {
					//暂时只给用户推送文本消息
					if (FeebackMsgTypeEnum.text.getKey() == feebackMsg.getMsgType()) {
						//给用户推送文本消息
						WxFeebackMsgVo feebackMsgVo = new WxFeebackMsgVo(openId, FeebackMsgTypeEnum.text.getValue());
						feebackMsgVo.setContent(feebackMsg.getContent());
						String respone = WeixinInterfaceUtil.sendMsg(accessToken, feebackMsgVo.getJSONMsg());
						LogUtils.info("respone : " + respone);
					} else if (FeebackMsgTypeEnum.image.getKey() == feebackMsg.getMsgType()) {
						//TODO
					} else if (FeebackMsgTypeEnum.voice.getKey() == feebackMsg.getMsgType()) {
						//TODO
					} else if (FeebackMsgTypeEnum.video.getKey() == feebackMsg.getMsgType()) {
						//TODO
					} else if (FeebackMsgTypeEnum.music.getKey() == feebackMsg.getMsgType()) {
						//TODO
					} else if (FeebackMsgTypeEnum.news.getKey() == feebackMsg.getMsgType()) {
						//TODO
					}
				}
			}
		} else {
			LogUtils.error(accountId + " 没有配置进数据库");
		}
	}
}
